package com.taomeishu.mailcrazy.fetch;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taomeishu.mailcrazy.CheckResult;
import com.taomeishu.mailcrazy.Mail;
import com.taomeishu.mailcrazy.MailExistChecker;
import com.taomeishu.mailcrazy.fetch.policy.DefaultSavePolicy;
import com.taomeishu.mailcrazy.fetch.policy.DelayPolicy;
import com.taomeishu.mailcrazy.fetch.policy.SavePolicy;

public class DefaultFetchMailService implements FetchMailService {

	private static final Logger log = LoggerFactory.getLogger(DefaultFetchMailService.class);
	
	private Map<String, FecthWorker> fecthEntries = new HashMap<String, FecthWorker>();
	
	private SavePolicy savePolicy = new DefaultSavePolicy();
	
	private EmailManager emailManager;
	
	private CharseqNumberManger charseqNumberManger;
	
	private volatile boolean proccess = true;
	
	public DefaultFetchMailService(EmailManager emailManager, CharseqNumberManger charseqNumberManger) {
		super();
		this.emailManager = emailManager;
		this.charseqNumberManger = charseqNumberManger;
	}

	@Override
	public void init() {
		for (Map.Entry<String, FecthWorker> entry : fecthEntries.entrySet()) {
			FecthWorker fecthWorker = entry.getValue();
			fecthWorker.init();
		}
	}

	@Override
	public void register(String domain, MailExistChecker mailExistChecker, DelayPolicy delayPolicy) {
		fecthEntries.put(domain, new FecthWorker(mailExistChecker, delayPolicy, savePolicy, domain, charseqNumberManger));
	}

	@Override
	public void start() {
		for (Map.Entry<String, FecthWorker> entry : fecthEntries.entrySet()) {
			FecthWorker fecthWorker = entry.getValue();
			FetchWorkerThread fetchWorkerThread = new FetchWorkerThread(fecthWorker);
			new Thread(fetchWorkerThread).start();
		}
	}
	
	public void stop() {
		proccess = false;
	}
	
	class FetchWorkerThread implements Runnable {

		private FecthWorker fecthWorker;
		
		public FetchWorkerThread(FecthWorker fecthWorker) {
			super();
			this.fecthWorker = fecthWorker;
		}

		@Override
		public void run() {
			while (proccess) {
				try {
					CheckResult checkResult = fecthWorker.execute();
					for (Mail mail : checkResult.getExistMails()) {
						if (mail != null) {
							emailManager.saveEmail(mail);
						}
					}
				} catch (Exception e) {
					log.error(fecthWorker.getDomain() + " fetch error", e);
					// 出现异常后1分钟后重试
					try {
						Thread.sleep(1 * 60 * 1000);
					} catch (InterruptedException e1) {
					}
				}
			}
		}
		
	}

}
